package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {


        try {
            SearchRequest request = new SearchRequest("hotel");
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            //全文搜索  文档分词搜索  如果没有输入内容就查全部
            String key = params.getKey();
            if (key==null|| "".equals(key)){
//                request.source().query(QueryBuilders.matchAllQuery());
                boolQuery.must(QueryBuilders.matchAllQuery());
            }else {
//                request.source().query(QueryBuilders.termQuery("all",key));
                boolQuery.must(QueryBuilders.termQuery("all",key));
            }
            //条件过滤
            //brand
            if (params.getBrand()!=null && !params.getBrand().equals("")){
                boolQuery.filter(QueryBuilders.termQuery("brand",params.getBrand()));
            }
            //city
            if (params.getCity()!=null && !params.getCity().equals("")){
                boolQuery.filter(QueryBuilders.termQuery("city",params.getCity()));
            }
            //starName
            if (params.getStarName()!=null && !params.getStarName().equals("")){
                boolQuery.filter(QueryBuilders.termQuery("starName",params.getStarName()));
            }
            //price
            if (params.getMinPrice()!=null && params.getMaxPrice()!=null){
                boolQuery.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice()));
            }
            //执行复合查询
            request.source().query(boolQuery);
            // 2.2.分页
            int page = params.getPage();
            int size = params.getSize();
            request.source().from((page - 1) * size).size(size);
            //排序 价格 距离
//            request.source().sort("price",SortOrder.ASC);
            String location = params.getLocation();
            if (location!=null && !location.equals("")){
                //执行排序
                request.source().sort(SortBuilders.geoDistanceSort("location",new GeoPoint(location))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS)
                );
            }
            //算分 加权 广告位
            FunctionScoreQueryBuilder isAD = QueryBuilders.functionScoreQuery(
                    //原始查询          新建算分数组
                    boolQuery, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                            // 其中的一个function score 元素
                            new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                    // 过滤条件 如果isad是true就加权
                                    QueryBuilders.termQuery("isAD", true),
                                    // 算分函数  加权 默认十倍
                                    ScoreFunctionBuilders.weightFactorFunction(10)
                            )
                    }
            );
            //执行加权
            request.source().query(isAD);
            SearchResponse search = client.search(request, RequestOptions.DEFAULT);
            return handleResponse(search);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    // 结果解析
    private PageResult handleResponse(SearchResponse response){
        SearchHits hits = response.getHits();
        long total = hits.getTotalHits().value;
        SearchHit[] hits1 = hits.getHits();
        ArrayList<HotelDoc> hotelDocs = new ArrayList<>();
        for (SearchHit hit : hits1) {
            String sourceAsString = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);
            hotelDocs.add(hotelDoc);
        }
        return new PageResult(total,hotelDocs);
    }
}
